package com.briup.bms.service.impl;

import com.briup.bms.bean.Department;
import com.briup.bms.common.exceptions.BmsServiceException;
import com.briup.bms.common.utils.ResultCode;
import com.briup.bms.dao.IDepartmentMapper;
import com.briup.bms.service.IDepartService;
import com.briup.bms.web.vm.DeptParamVM;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Set;

@Service
public class DeptServiceImpl implements IDepartService {

    @Autowired
    private IDepartmentMapper deptMapper;

    @Override
    public PageInfo<Department> findByCondition(int pageNum, int pageSize,
                                                String name, Integer regionId) {
        name = ObjectUtils.isEmpty(name) ? name : "%" + name + "%";
        PageHelper.startPage(pageNum, pageSize);
        List<Department> list =
                deptMapper.findByCondition(name, regionId);
        System.out.println(new PageInfo<>(list));
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdate(DeptParamVM deptVM) {
//		Department entity = new Department();
//		entity.setId(dept.getId());
//		entity.setName(dept.getName());
//		entity.setRegionId(dept.getRegionId());
        //BeanUtils.copyPorperties是javaBean对象属性的copy，判断属性名和类型一致，会自动copy赋值。
//		BeanUtils.copyProperties(dept, entity);
        Department entity = new Department();
        BeanUtils.copyProperties(deptVM, entity);
        System.out.println(entity);

        //无论是更新或者保存，都需要判断，
        //在指定区域下是否有同名的部门存在，如果有操作失败，如果没有操作成功。
        if (deptVM.getId() != null) {
            //更新
            deptMapper.updateById(entity);
        } else {
            //保存
            deptMapper.insert(entity);
        }
    }

    @Override
    public void deleteDepartment(String department) {
        int row = deptMapper.deleteDepartment(department);
        if (row <= 0) {
            throw new BmsServiceException(ResultCode.DATA_NOT_EXIST, "删除失败，数据不存在");
        }
    }

    @Override
    public PageInfo<Department> findByPageInfo(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Department> list = deptMapper.findByPageInfo();
        return new PageInfo<>(list);
    }

    @Override
    public Department findBydeptId(Integer deptId) {
        Department department = deptMapper.findDeptById(deptId);
        if (ObjectUtils.isEmpty(department)) {
            throw new BmsServiceException(ResultCode.DATA_NOT_EXIST, "数据不存在");
        }
        return department;
    }

    @Override
    public void batchDeleteDept(Set<Integer> departmentIds) {
        deptMapper.batchDelete(departmentIds);
    }

}
